<template>
  <div class="story-detail">
    <div class="container">
      <div v-if="!story" class="loading-state">
        <div class="spinner"></div>
        <p>加载故事中...</p>
      </div>

      <div v-else class="story-content">
        <!-- Story Header -->
        <div class="story-header">
          <div class="story-meta-info">
            <div class="breadcrumb">
              <router-link to="/library" class="breadcrumb-link">
                <ArrowLeft :size="16" />
                返回故事库
              </router-link>
            </div>
            
            <h1 class="story-title">{{ story.title }}</h1>
            
            <div class="story-info">
              <span class="story-category">{{ story.category }}</span>
              <div class="story-stats">
                <div class="stat">
                  <Eye :size="16" />
                  <span>{{ formatNumber(story.views) }} 阅读</span>
                </div>
                <div class="stat">
                  <Heart :size="16" />
                  <span>{{ story.likes }} 点赞</span>
                </div>
                <div class="stat">
                  <MessageCircle :size="16" />
                  <span>{{ story.comments_count || story.comments?.length || 0 }} 评论</span>
                </div>
              </div>
            </div>

            <div class="author-info">
              <div class="author-avatar">
                <img v-if="story.author_avatar && story.author_avatar !== '/default-avatar.png'" 
                     :src="story.author_avatar" 
                     alt="作者头像" 
                     class="avatar-img" />
                <Users v-else :size="20" />
              </div>
              <div class="author-details">
                <div class="author-name">{{ story.author_name || story.author }}</div>
                <div class="publish-date">发布于 {{ formatDate(story.published_at || story.publishedAt) }}</div>
              </div>
            </div>
          </div>

          <div class="story-actions">
            <button
              @click="toggleLike"
              :class="{ liked: isUserLiked, disabled: !authStore.isAuthenticated }"
              class="action-btn like-btn"
              :title="authStore.isAuthenticated ? '' : '请先登录后点赞'"
            >
              <Heart :size="20" :fill="isUserLiked ? 'currentColor' : 'none'" />
              <span>{{ isUserLiked ? '已点赞' : '点赞' }}</span>
            </button>
            
            <button @click="shareStory" class="action-btn">
              <Share2 :size="20" />
              <span>分享</span>
            </button>
            
            <button @click="toggleBookmark" class="action-btn">
              <Bookmark :size="18" :fill="isBookmarked ? 'currentColor' : 'none'" />
              <span>{{ isBookmarked ? '已收藏' : '收藏' }}</span>
            </button>
          </div>
        </div>

        <!-- Story Content -->
        <div class="story-body">
          <div class="story-text" v-html="formatStoryContent(story.content)"></div>
        </div>

        <!-- Story Tags -->
        <div v-if="story.tags && story.tags.length" class="story-tags">
          <h3>标签</h3>
          <div class="tags-list">
            <span 
              v-for="tag in story.tags" 
              :key="tag"
              class="tag"
            >
              {{ tag }}
            </span>
          </div>
        </div>

        <!-- Comments Section -->
        <div class="comments-section">
          <div class="comments-header">
            <h3>评论 ({{ story.comments_count || story.comments?.length || 0 }})</h3>
          </div>

          <!-- Add Comment Form -->
          <div v-if="authStore.isAuthenticated" class="add-comment">
            <div class="comment-form">
              <textarea
                v-model="newComment"
                class="comment-input"
                placeholder="写下你的想法..."
                rows="3"
              ></textarea>
              <div class="comment-actions">
                <button
                  @click="addComment"
                  :disabled="!newComment.trim()"
                  class="btn btn-primary"
                >
                  <Send :size="16" />
                  发表评论
                </button>
              </div>
            </div>
          </div>

          <div v-else class="login-prompt">
            <p>请先登录后参与评论讨论</p>
          </div>

          <!-- Comments List -->
          <div class="comments-list">
            <div v-if="(story.comments_count || story.comments?.length || 0) === 0" class="no-comments">
              <MessageCircle :size="48" />
              <p>还没有评论，来说说你的想法吧！</p>
            </div>

            <div
              v-for="comment in (story.comments || [])"
              :key="comment.id"
              class="comment-item"
            >
              <div class="comment-avatar">
                <img v-if="comment.author_avatar && comment.author_avatar !== '/default-avatar.png'" 
                     :src="comment.author_avatar" 
                     alt="评论者头像" 
                     class="avatar-img" />
                <Users v-else :size="20" />
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="comment-author">{{ comment.author_name || comment.author }}</span>
                  <span class="comment-date">{{ formatDate(comment.created_at || comment.createdAt) }}</span>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-actions">
                  <button
                    @click="toggleCommentLike(comment.id)"
                    :class="{ liked: isCommentLiked(comment.id) }"
                    class="comment-action"
                  >
                    <Heart :size="14" :fill="isCommentLiked(comment.id) ? 'currentColor' : 'none'" />
                    <span>{{ comment.likes || 0 }}</span>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Related Stories -->
        <div class="related-stories">
          <h3>相关故事</h3>
          <div class="related-grid">
            <div
              v-for="relatedStory in relatedStories"
              :key="relatedStory.id"
              class="related-item"
              @click="goToStory(relatedStory.id)"
            >
              <div class="related-card card">
                <h4>{{ relatedStory.title }}</h4>
                <p>{{ getExcerpt(relatedStory.content) }}</p>
                <div class="related-meta">
                  <span class="related-author">{{ relatedStory.author }}</span>
                  <div class="related-stats">
                    <span><Eye :size="12" /> {{ formatNumber(relatedStory.views) }}</span>
                    <span><Heart :size="12" /> {{ relatedStory.likes }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStoriesStore } from '../stores/stories'
import { useAuthStore } from '../stores/auth'
import { useToast } from 'vue-toastification'
import { gsap } from 'gsap'
import apiClient from '../api/axios'
import { API_ENDPOINTS } from '../api/config'
import {
  ArrowLeft,
  Eye,
  Heart,
  MessageCircle,
  Users,
  Share2,
  Bookmark,
  Send
} from 'lucide-vue-next'

const route = useRoute()
const router = useRouter()
const storiesStore = useStoriesStore()
const authStore = useAuthStore()
const toast = useToast()

const story = ref(null)
const newComment = ref('')
const isBookmarked = ref(false)
const likedComments = ref(new Set())

const isUserLiked = computed(() => {
  if (!authStore.isAuthenticated || !story.value) return false
  // 优先使用后端返回的is_liked状态
  return story.value.is_liked || false
})

const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  }
})

const relatedStories = computed(() => {
  if (!story.value) return []
  
  return storiesStore.publishedStories
    .filter(s => s.id !== story.value.id && s.category === story.value.category)
    .slice(0, 3)
})

const formatNumber = (num) => {
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k'
  }
  return num.toString()
}

const formatDate = (dateString) => {
  if (!dateString) return '未知时间'
  
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return '未知时间'
  
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0 || diffDays === 1) return '今天'
  if (diffDays === 2) return '昨天'
  if (diffDays <= 7) return `${diffDays}天前`
  if (diffDays <= 30) return `${Math.ceil(diffDays / 7)}周前`
  if (diffDays <= 365) return `${Math.ceil(diffDays / 30)}个月前`
  return `${Math.ceil(diffDays / 365)}年前`
}

const formatStoryContent = (content) => {
  return content.replace(/\n/g, '<br>')
}

const getExcerpt = (content) => {
  return content.length > 100 ? content.substring(0, 100) + '...' : content
}

const loadStory = async () => {
  const storyId = parseInt(props.id)
  
  try {
    // 先尝试从API获取故事详情
    await storiesStore.getStoryDetail(storyId)
    story.value = storiesStore.currentStory
    
    // 初始化收藏状态
    isBookmarked.value = story.value?.is_bookmarked || false
    
    // 初始化评论点赞状态
    likedComments.value.clear()
    if (story.value?.comments) {
      story.value.comments.forEach(comment => {
        if (comment.is_liked) {
          likedComments.value.add(comment.id)
        }
      })
    }
  } catch (error) {
    // 如果API获取失败，尝试从本地stories中查找
    const foundStory = storiesStore.stories.find(s => s.id === storyId)
    
    if (foundStory) {
      story.value = foundStory
      // 初始化收藏状态
      isBookmarked.value = foundStory.is_bookmarked || false
      
      // 初始化评论点赞状态
      likedComments.value.clear()
      if (foundStory.comments) {
        foundStory.comments.forEach(comment => {
          if (comment.is_liked) {
            likedComments.value.add(comment.id)
          }
        })
      }
    } else {
      toast.error('故事不存在')
      router.push('/library')
    }
  }
}

const toggleLike = async () => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    return
  }
  
  // 立即更新UI，提供即时反馈
  const previousLiked = story.value.is_liked
  const previousLikes = story.value.likes
  
  // 乐观更新UI
  story.value.is_liked = !previousLiked
  story.value.likes = previousLiked ? previousLikes - 1 : previousLikes + 1
  
  // 添加动画效果
  const likeBtn = document.querySelector('.like-btn')
  if (likeBtn) {
    likeBtn.classList.add('pulse-animation')
    setTimeout(() => likeBtn.classList.remove('pulse-animation'), 300)
  }
  
  try {
    const result = await storiesStore.likeStory(story.value.id)
    if (result.success) {
      // 同步后端返回的准确数据
      story.value.likes = result.data.likes
      story.value.is_liked = result.data.is_liked
      
      if (result.data.is_liked) {
        toast.success('点赞成功！')
      } else {
        toast.info('已取消点赞')
      }
    }
  } catch (error) {
    // 失败时回滚UI状态
    story.value.is_liked = previousLiked
    story.value.likes = previousLikes
    toast.error('操作失败：' + (error.message || '请重试'))
  }
}

const toggleBookmark = async () => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    return
  }
  
  try {
    // 发送收藏API请求
    const response = await apiClient.post(API_ENDPOINTS.STORY_BOOKMARK(story.value.id))
    
    console.log('收藏响应:', response)
    
    // 更新本地状态
    if (response.success) {
      isBookmarked.value = response.is_bookmarked
      
      // 更新story对象的is_bookmarked字段
      if (story.value) {
        story.value.is_bookmarked = response.is_bookmarked
      }
      
      // 更新storiesStore中的数据
      const storyInStore = storiesStore.stories.find(s => s.id === story.value.id)
      if (storyInStore) {
        storyInStore.is_bookmarked = response.is_bookmarked
      }
      
      toast.success(response.message || (isBookmarked.value ? '已收藏' : '已取消收藏'))
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    toast.error('操作失败，请重试')
  }
}

const shareStory = () => {
  if (navigator.share) {
    navigator.share({
      title: story.value.title,
      text: getExcerpt(story.value.content),
      url: window.location.href
    })
  } else {
    navigator.clipboard.writeText(window.location.href)
    toast.success('链接已复制到剪贴板')
  }
}

const addComment = async () => {
  if (!newComment.value.trim()) return
  
  try {
    await storiesStore.addComment(story.value.id, newComment.value)
    newComment.value = ''
    // toast已在store中显示
  } catch (error) {
    toast.error('评论失败：' + (error.message || '请重试'))
  }
}

const isCommentLiked = (commentId) => {
  return likedComments.value.has(commentId)
}

const toggleCommentLike = async (commentId) => {
  if (!authStore.isAuthenticated) {
    toast.warning('请先登录')
    return
  }
  
  // 找到对应的评论
  const comment = story.value.comments?.find(c => c.id === commentId)
  if (!comment) return
  
  // 保存之前的状态，用于失败时回滚
  const wasLiked = likedComments.value.has(commentId)
  const previousLikes = comment.likes
  
  try {
    // 立即更新UI，提供即时反馈
    if (wasLiked) {
      likedComments.value.delete(commentId)
      comment.likes = Math.max(0, (comment.likes || 0) - 1)
    } else {
      likedComments.value.add(commentId)
      comment.likes = (comment.likes || 0) + 1
    }
    
    // 发送API请求
    const response = await apiClient.post(
      API_ENDPOINTS.COMMENT_LIKE(story.value.id, commentId)
    )
    
    console.log('评论点赞响应:', response)
    
    // 使用后端返回的实际点赞数
    if (response.success && response.data) {
      comment.likes = response.data.likes
      
      // 根据后端返回的action更新状态
      if (response.data.action === 'liked') {
        likedComments.value.add(commentId)
      } else {
        likedComments.value.delete(commentId)
      }
    }
  } catch (error) {
    // 失败时回滚UI状态
    if (wasLiked) {
      likedComments.value.add(commentId)
    } else {
      likedComments.value.delete(commentId)
    }
    comment.likes = previousLikes
    
    console.error('评论点赞失败:', error)
    toast.error('操作失败，请重试')
  }
}

const handleLogin = () => {
  authStore.login({
    id: Date.now(),
    name: '新用户',
    email: 'user@example.com',
    role: 'user'
  })
  toast.success('登录成功！')
}

const goToStory = (storyId) => {
  router.push(`/story/${storyId}`)
}

watch(() => props.id, loadStory, { immediate: true })

onMounted(() => {
  // Animate story content
  gsap.fromTo('.story-content > *',
    { opacity: 0, y: 30 },
    {
      opacity: 1,
      y: 0,
      duration: 0.8,
      stagger: 0.1,
      ease: 'power2.out'
    }
  )
})
</script>

<style scoped>
.story-detail {
  padding: var(--spacing-2xl) 0;
  min-height: 100vh;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: var(--text-secondary);
}

.story-content {
  max-width: 800px;
  margin: 0 auto;
}

.story-header {
  margin-bottom: var(--spacing-3xl);
  padding-bottom: var(--spacing-2xl);
  border-bottom: 1px solid var(--border-color);
}

.breadcrumb {
  margin-bottom: var(--spacing-lg);
}

.breadcrumb-link {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-secondary);
  text-decoration: none;
  transition: color var(--transition-fast);
}

.breadcrumb-link:hover {
  color: var(--primary-color);
}

.story-title {
  font-size: var(--font-size-3xl);
  margin-bottom: var(--spacing-lg);
  line-height: 1.2;
}

.story-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
  flex-wrap: wrap;
}

.story-category {
  background: var(--gradient-primary);
  color: white;
  padding: var(--spacing-xs) var(--spacing-md);
  border-radius: var(--radius-lg);
  font-size: var(--font-size-sm);
  font-weight: 500;
}

.story-stats {
  display: flex;
  gap: var(--spacing-lg);
}

.stat {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  color: var(--text-muted);
  font-size: var(--font-size-sm);
}

.author-info {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-xl);
}

.author-avatar {
  width: 48px;
  height: 48px;
  background: var(--bg-tertiary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  overflow: hidden;
}

.author-avatar .avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.author-name {
  font-weight: 500;
  color: var(--text-primary);
}

.publish-date {
  font-size: var(--font-size-sm);
  color: var(--text-muted);
}

.story-actions {
  display: flex;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  padding: var(--spacing-sm) var(--spacing-lg);
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
  font-size: var(--font-size-sm);
}

.action-btn:hover {
  background: var(--bg-tertiary);
  color: var(--text-primary);
}

.action-btn.pulse-animation {
  animation: pulse 0.3s ease-in-out;
}

.like-btn.liked {
  color: var(--error-color);
  border-color: var(--error-color);
  background: rgba(255, 107, 107, 0.1);
}

.like-btn.pulse-animation {
  animation: pulse 0.3s ease-in-out;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.15);
  }
  100% {
    transform: scale(1);
  }
}

.like-count {
  margin-left: 4px;
  font-weight: 500;
}

.story-body {
  margin-bottom: var(--spacing-3xl);
}

.story-text {
  font-size: var(--font-size-lg);
  line-height: 1.8;
  color: var(--text-secondary);
}

.story-tags {
  margin-bottom: var(--spacing-3xl);
}

.story-tags h3 {
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
}

.tags-list {
  display: flex;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.tag {
  padding: var(--spacing-xs) var(--spacing-md);
  background: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.comments-section {
  margin-bottom: var(--spacing-3xl);
}

.comments-header h3 {
  margin-bottom: var(--spacing-xl);
  color: var(--text-primary);
}

.add-comment {
  margin-bottom: var(--spacing-2xl);
}

.comment-form {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  border: 1px solid var(--border-color);
}

.comment-input {
  width: 100%;
  background: var(--bg-tertiary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  color: var(--text-primary);
  resize: vertical;
  margin-bottom: var(--spacing-md);
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.login-prompt {
  text-align: center;
  padding: var(--spacing-xl);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  margin-bottom: var(--spacing-2xl);
}

.login-link {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
  text-decoration: underline;
}

.comments-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.no-comments {
  text-align: center;
  padding: var(--spacing-3xl);
  color: var(--text-muted);
}

.comment-item {
  display: flex;
  gap: var(--spacing-md);
  padding: var(--spacing-lg);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  margin-bottom: var(--spacing-lg);
}

.comment-avatar {
  width: 40px;
  height: 40px;
  background: var(--bg-tertiary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  flex-shrink: 0;
  overflow: hidden;
}

.comment-avatar .avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-sm);
}

.comment-author {
  font-weight: 500;
  color: var(--text-primary);
}

.comment-date {
  font-size: var(--font-size-sm);
  color: var(--text-muted);
}

.comment-text {
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: var(--spacing-sm);
}

.comment-actions {
  display: flex;
  gap: var(--spacing-md);
}

.comment-action {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  background: none;
  border: none;
  color: var(--text-muted);
  cursor: pointer;
  transition: color var(--transition-fast);
  font-size: var(--font-size-sm);
}

.comment-action:hover {
  color: var(--text-primary);
}

.comment-action.liked {
  color: var(--error-color);
}

.related-stories h3 {
  margin-bottom: var(--spacing-xl);
  color: var(--text-primary);
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: var(--spacing-lg);
}

.related-item {
  cursor: pointer;
}

.related-card {
  height: 100%;
  transition: all var(--transition-normal);
}

.related-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-xl);
}

.related-card h4 {
  margin-bottom: var(--spacing-sm);
  color: var(--text-primary);
}

.related-card p {
  color: var(--text-secondary);
  line-height: 1.6;
  margin-bottom: var(--spacing-md);
}

.related-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: var(--spacing-sm);
  border-top: 1px solid var(--border-color);
}

.related-author {
  font-size: var(--font-size-sm);
  color: var(--text-muted);
}

.related-stats {
  display: flex;
  gap: var(--spacing-md);
  font-size: var(--font-size-xs);
  color: var(--text-muted);
}

.related-stats span {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

/* Mobile Styles */
@media (max-width: 768px) {
  .story-content {
    padding: 0 var(--spacing-md);
  }

  .story-title {
    font-size: var(--font-size-2xl);
  }

  .story-info {
    flex-direction: column;
    align-items: flex-start;
    gap: var(--spacing-md);
  }

  .story-actions {
    width: 100%;
  }

  .action-btn {
    flex: 1;
    justify-content: center;
  }

  .related-grid {
    grid-template-columns: 1fr;
  }
}
</style>
